package com.example.pdfandword.vo;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;

public class PrintUtil {
	/**
	 * Logger for this class
	 */
 	public static boolean printFile(String filePath){
		boolean returnFlg = false;
		ComThread.InitSTA();
		ActiveXComponent xl = new ActiveXComponent("Excel.Application");
		try {

			// 不打开文档
//			Dispatch.put(xl, "Visible", new Variant(true));
			Dispatch.put(xl, "Visible", new Variant(false));
			Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
			// win下路径处理(把根目录前的斜杠删掉)
//			filePath = filePath.replace("D:/","D:/");
			// 判断文件是否存在
			boolean fileExistFlg = fileExist(filePath);
			if (fileExistFlg) {
				Dispatch excel= Dispatch.call(workbooks,"Open",filePath).toDispatch();

//				Dispatch currentSheet = Dispatch.get(excel,"ActiveSheet").toDispatch();
//				Dispatch pageSetup = Dispatch.get(currentSheet, "PageSetup").toDispatch();
//				 Dispatch.put(pageSetup, "PaperSize", new Integer(papersize));//A3是8，A4是9，A5是11等等
//				 int ps = Dispatch.get(pageSetup, "PaperSize").toInt();
//				System.out.println("ps=" + ps);
//				Object[] object = new Object[8];
//				object[0] = Variant.VT_MISSING;
//				object[1] = Variant.VT_MISSING;
//				object[2] = Variant.VT_MISSING;
//				object[3] = new Boolean(false);
//				object[4] = Variant.VT_MISSING;
//				object[5] = new Boolean(false);
//				object[6] = Variant.VT_MISSING;
//				object[7] = Variant.VT_MISSING;
				// 开始打印
				Dispatch.get(excel,"PrintOut");
				returnFlg = true;
				//关闭文档
               Dispatch.call(excel, "Close", new Variant(true));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 始终释放资源
			xl.invoke("Quit", new Variant[] {});
			ComThread.Release();
		}
		return returnFlg;
	}
	/**
	 * 判断文件是否存在.
	 * @param filePath  文件路径
	 * @return
	 */
	private static boolean fileExist(String filePath) {
		boolean flag = false;
		try {
			File file = new File(filePath);
			flag = file.exists();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
}
